package com.linsen.core.cloud.filter;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.linsen.core.common.constant.TenantConstant;
import com.linsen.core.common.context.TenantContextHolder;
import com.linsen.core.common.model.User;
import com.linsen.core.common.util.SecurityUtil;
import com.linsen.core.redis.util.RedisSecurityUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Optional;

/**
 * 租户上下文过滤器
 *
 * @author zhaoyong
 * @date 2023/3/13
 */
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE + 2)
@RequiredArgsConstructor
public class TenantContextHolderFilter extends GenericFilterBean {
    private final RedisSecurityUtil redisSecurityUtil;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        try {
            // 优先取请求参数中的tenantId值
            String tenantId = request.getHeader(TenantConstant.LINSEN_TENANT_ID);
            if (StrUtil.isBlank(tenantId)) {
                String token = Optional.ofNullable(SecurityUtil.getHeaderToken(request)).orElse(SecurityUtil.getQueryToken(request));
                if (StrUtil.isNotBlank(token)) {
                    // 取token中的tenantId值
                    try {
                        User user = this.redisSecurityUtil.getUser(token);
                        if (ObjectUtil.isNotNull(user)) {
                            tenantId = String.valueOf(user.getTenantId());
                        }
                    }catch (Exception e){

                    }
                }
            }
            log.debug("tenant context holder filter tenant id :{}", tenantId);
            if (StrUtil.isNotBlank(tenantId)) {
                TenantContextHolder.setTenantId(tenantId);
            } else {
                if (StrUtil.isBlank(TenantContextHolder.getTenantId())) {
                    TenantContextHolder.setTenantId(TenantConstant.TENANT_ID_DEFAULT);
                }
            }
            filterChain.doFilter(request, response);
        } finally {
            TenantContextHolder.removeTenantId();
        }
    }
}

